package ex02.pyrmont;

import com.sky.JULLog.MyLogger;

import java.net.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * 丐版 tomcat 升级版 v1  http://localhost:8080/servlet/PrimitiveServlet
 */
public class TrashyTomcatV1 {

    /**
     * WEB_ROOT is the directory where our HTML and other files reside.
     * For this package, WEB_ROOT is the "webroot" directory under the working
     * directory.
     * The working directory is the location in the file system
     * from where the java command was invoked.
     */
    // shutdown command
    static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    private static final String SERVER_IP = "127.0.0.1";
    private final static int PORT = 8080;
    // the shutdown command received
    private boolean shutdown = false;

    private  static Logger  log = MyLogger.getLogger(TrashyTomcatV1.class);


    private void await() {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(PORT, 1, InetAddress.getByName(SERVER_IP));
        } catch (BindException | UnknownHostException e) {
            log.log(  Level.SEVERE  , "出现异常, 请检查端口占用, 丐版 tomcat 即将退出...." , e);
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("丐版tomcat 启动.......");
        // Loop waiting for a request
        while (!shutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                // create Request object and parse
                RequestV1 requestV1 = new RequestV1(input);
                requestV1.parse();

                // create ResponseV1 object ,  为啥 servlet 能够 输出到浏览器中, 就是因为 这个 socket  中的 output 给了 response 对象;
                ResponseV1 responseV1 = new ResponseV1(output);
                responseV1.setRequest(requestV1);

                // check if this is a request for a servlet or a static resource
                // a request for a servlet begins with "/servlet/"
                if (requestV1.getUri()==null){
                    continue;
                }

                if (requestV1.getUri().startsWith("/servlet/")) {
                    ServletProcessorV1 servletProcessorV1 = new ServletProcessorV1();
                    servletProcessorV1.process(requestV1, responseV1);

                    ServletProcessorV2 servletProcessorV2 = new ServletProcessorV2();
                    servletProcessorV2.process(requestV1, responseV1);


                } else {
                    StaticResourceProcessor staticResourceProcessor = new StaticResourceProcessor();
                    staticResourceProcessor.process(requestV1, responseV1);
                }

                // Close the socket
                socket.close();
                //check if the previous URI is a shutdown command
                shutdown = requestV1.getUri().equals(SHUTDOWN_COMMAND);
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    public static void main(String[] args) {
        TrashyTomcatV1 server = new TrashyTomcatV1();
        server.await();
    }
}
